import { URL, fileURLToPath } from 'node:url'
import process from 'node:process'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

// 浏览器兼容
import legacy from '@vitejs/plugin-legacy'

// UI组件自动引入
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

// 图标引入
import IconsResolver from 'unplugin-icons/resolver'

// iconfy
import Icons from 'unplugin-icons/vite'
import UnoCSS from 'unocss/vite'
import eslint from 'vite-plugin-eslint'
import viteCompression from 'vite-plugin-compression'

// 打包依赖分析
import { visualizer } from 'rollup-plugin-visualizer'

// html模板
import { createHtmlPlugin } from 'vite-plugin-html'
import postcssPresetEnv from 'postcss-preset-env'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // const isProduction: unknown = loadEnv(mode, process.cwd()).VITE_ENV === 'production'
  return {
    plugins: [
      vue(),
      eslint(),
      legacy({
        targets: ['defaults', 'not IE 11']
      }),
      AutoImport({
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            // 其他工具API引入方式
            '@vueuse/core': [
              // vueuse工具集的内容太多不适合全局引入，可以按照如下方式引入需要使用的hooks
              // named imports
              'useMouse', // import { useMouse } from '@vueuse/core',
              // alias
              ['useFetch', 'useMyFetch'] // import { useFetch as useMyFetch } from '@vueuse/core',
            ]
          }
        ],
        resolvers: [AntDesignVueResolver(), IconsResolver({})],
        vueTemplate: true,
        eslintrc: {
          enabled: false, // 是否自动生成 eslint 规则，建议生成之后设置 false
          filepath: './.eslintrc-auto-import.json' // 指定自动导入函数 eslint 规则的文件
        },
        dts: 'src/types/auto-imports.d.ts'
      }),
      Components({
        // 自定义组件所在文件夹，默认位置
        dirs: ['src/components'],
        resolvers: [
          AntDesignVueResolver({ importStyle: 'less', resolveIcons: true }),
          IconsResolver()
        ],
        extensions: ['vue'], // 文件扩展
        // 配置type文件生成位置
        dts: 'src/types/components.d.ts'
      }),
      Icons({
        // 自动安装图标库
        autoInstall: true
      }),
      UnoCSS({}),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            webTitle: loadEnv(mode, process.cwd()).VITE_WEB_TITLE
          }
        }
      }),
      visualizer()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    base: './',
    server: {
      host: '0.0.0.0',
      // port: 8082,
      open: true,
      proxy: {
        // 接口服务代理转发
        '/api': {
          target: 'https://mock.apifox.cn/m1/2832701-0-default/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        },
        '/ws': {
          target: 'ws://localhost:9092/',
          changeOrigin: true,
          ws: true,
          rewrite: path => path.replace(/^\/ws/, '')
        },
        '/mock': {
          target: 'https://mock.apifox.cn/m1/2832701-0-default/',
          changeOrigin: true
          // rewrite: path => path.replace(/^\/mock/, '')
        }
      }
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      },
      // minify: 'esbuild'
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    },
    // esbuild: {
    //   drop: isProduction ? ['console', 'debugger'] : []
    // },
    css: {
      postcss: {
        plugins: [postcssPresetEnv()]
        // plugins: []
      },
      preprocessorOptions: {
        less: {
          // 引入全局less变量文件
          additionalData: `@import "@/style/variables.less";`
        }
      }
    }
  }
})
